/**
 * @description 服务
 */

import { objecter, Service, DataService, filer, strer, DberDataBase, SqliteDataBase } from '@daelui/dogjs/dist/components'
import storeStorage, { StoreStorage } from './store/store-storage.js'
import storeUni, { StoreUni } from './store/store-uni.js'
import storeFile, { StoreFile } from './store/store-file.js'
import request from '../uview-ui/libs/request/index.js'
import bridgeDiseaseTable from './store/tables/bridge-disease.js'
import bridgeDiseaseImageTable from './store/tables/bridge-disease-image.js'
import tunnelDiseaseTable from './store/tables/tunnel-disease.js'
import tunnelDiseaseImageTable from './store/tables/tunnel-disease-image.js'

// const storeStorage = storeUni
// const StoreStorage = StoreUni
const piper = {}

// 常量键
const keys = {
  storeType: 'uni-store',
  fileType: 'uni-file',
  dict: 'uni-dict',
  dept: 'uni-dept',
  route: 'uni-route',
  bridge: 'uni-bridge', // 桥梁根键
  bd: 'uni-bridgeDisease', // 桥梁病害根键
  bridgeList: 'bridgeList', // 桥梁列表
  bridgeComponentList: 'bridgeComponentList', // 桥梁组件
  bridgeProjectList: 'bridgeProjectList', // 检查项目
  bridgeInspectionList: 'bridgeInspectionList', // 检查计划
  bridgeDiseaseList: 'bridgeDiseaseList', // 病害列表
  bridgeDiseaseImageList: 'bridgeDiseaseImageList', // 桥梁病害图片列表
  bridgeSiteInfoList: 'bridgeSiteInfoList', // 桥梁现场信息
  bridgeDiseaseTagsList: 'uni-bridgeDiseaseTagsList', // 病害位置
  bridgeDiseaseTypeList: 'uni-bridgeDiseaseTypeList', // 病害类型
  bridgeDiseaseTypeScaleList: 'uni-bridgeDiseaseTypeScaleList', // 病害标度
  bridgeSimpleTargetList: 'uni-bridgeSimpleTargetList', // 病害标度说明
  bridgeStructTypeList: 'uni-bridgeStructTypeList', // 桥梁结构列表

  tunnel: 'uni-tunnel', // 隧道根键
  tunnelList: 'tunnel', // 隧道列表
  tunnelPartList: 'uni-tunnelPartList', // 隧道部件列表
  tunnelComponentList: 'tunnelComponentList', // 隧道组件
  tunnelProjectList: 'tunnelProjectList', // 检查项目
  tunnelInspectionList: 'tunnelInspectionList', // 检查计划
  tunnelDiseaseList: 'tunnelDiseaseList', // 病害列表
  tunnelDiseaseImageList: 'tunnelDiseaseImageList', // 隧道病害图片列表
  tunnelSiteInfoList: 'tunnelSiteInfoList', // 隧道现场信息
  tunnelDiseaseLocationList: 'uni-tunnelDiseaseLocationList', // 病害部位
  tunnelDiseaseTagsList: 'uni-tunnelDiseaseTagsList', // 病害位置
  tunnelDiseaseTypeList: 'uni-tunnelDiseaseTypeList', // 病害类型
  tunnelDiseaseTypeScaleList: 'uni-tunnelDiseaseTypeScaleList', // 病害标度
  tunnelSimpleTargetList: 'uni-tunnelSimpleTargetList', // 病害标度说明

  td: 'uni-tunnelDisease', // 隧道病害根键
}

// 当前用户
const currentUser = {
  userName: ''
}

// 是否是APP环境
let isPlus = false
// #ifdef APP-PLUS
isPlus = true
// #endif
const StoreClass = StoreStorage // isPlus ? StoreFile : StoreStorage
const storeClass = storeStorage // isPlus ? storeFile : storeStorage

// 存储管理
class StorePipe {
  constructor () {
    this.storeMap = new Map()
  }

  getItem (key) {
    let store = this.getStore(key)
    return store.getItem.apply(store, arguments)
  }

  setItem (key, value, options) {
    let store = this.getStore(key)
    return store.setItem.apply(store, arguments)
  }

  getStore (key) {
    let store = this.storeMap.get(key)
    if (!store) {
      store = new StoreClass()
      store.setKey(key)
      this.storeMap.set(key, store)
    }
    return store
  }
  
  setKey () {}
}

class UService extends DataService {
  constructor ({ service }) {
    super()
    this.service = service
    storeStorage.setKey(keys.storeType)
    this.registerStore(keys.storeType, storeStorage)
    let store = storeClass
    store.setKey(keys.fileType)
    this.registerStore(keys.fileType, store)
  }

  /**
   * @function 处理配置参数
   * @return {Object}
   * */
  process () {
    return Service.prototype.process.apply(this, arguments)
  }

  /**
   * @function 发送请求数据
   * @param {Object} options // 配置对象
   * @return {Promise}
  */
  _send (options) {
    // 显示进度条
    // if(request.config.showLoading && options.showLoading !== false) {
    // 	uni.showLoading({
    // 		title: request.config.loadingText,
    // 		mask: request.config.loadingMask
    // 	})
    // }
    // 是否缓存数据或是否缓冲相同的请求
    let defer = this.getCache(options) || this.getBuffer(options)
    defer = Promise.resolve(defer).catch(defer).then(res => {
      // 无数据则发送请求
      if (!res) {
        let data = { ...(options.data || {}) }
        for(let key in data) {
          if (data[key] === undefined || data[key] === null) {
            delete data[key]
          }
        }
        res = this.service[options.method](options.url, data, options.header || options.headers)
        // 缓冲请求
        this.setBuffer(options, res)
      }
      uni.hideLoading()
      return res
    })
    return defer
  }

  /**
   * @function 解析响应数据
   * @param {Object} result // 数据对象
   * @return {String}
  */
  resolveResponse (res) {
    return res
  }

  /**
   * @function 默认配置
   * @return {Object}
  */
  getDefaults () {
    return {
      url: '',
      method: 'POST',
      data: '',
      // 请求头对象
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    }
  }
}

export default UService

// 根据用户生成keys
export const setUserKeys = function (user) {
  user = user || {}
  let userName = user.userName || ''
  // 根据用户生成keys
  Object.keys(keys).forEach(key => {
    // 非uni开头则为用户级key
    if (!/^uni/.test(keys[key])) {
      keys[key] = keys[key].replace(/-user-.+/, '') + '-user-' + userName
    }
  })
  currentUser.userName = userName
  // 切换数据库
  changeDB(currentUser)
}

// 设置病害存储器
export const changeDB = function (user) {
  // 数据库类
  const DataBase = isPlus ? SqliteDataBase : DberDataBase
  let db = new DataBase({
    dbName: 'db_' + user.userName,
    dbTables: [
      bridgeDiseaseTable,
      bridgeDiseaseImageTable,
      tunnelDiseaseTable,
      tunnelDiseaseImageTable
    ]
  })
  piper.dber = db
}

export {
  isPlus, keys, currentUser, piper,
  StoreClass, StoreStorage,
  storeStorage, storeFile,
  StorePipe
}
